//
//  SelectTagsViewController.m
//  PigMarket
//
//  Created by Felix on 2019/3/25.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "SelectTagsViewController.h"

#import "SelectTagsCellFlowLayout.h"
#import "HButtonView.h"
#import "TagsHeaderView.h"
/*************************************** SelectTagsCell *********************************************/

@interface SelectTagsCell ()


@end

@implementation SelectTagsCell

#pragma mark - init method
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.cornerRadius = 15;
        self.layer.borderWidth = 1;
        self.layer.borderColor = [UIColor colorWithHexString:@"#cccccc"].CGColor;
        [self.contentView addSubview:self.title];
        [self.title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.top.mas_equalTo(4);
            make.right.mas_equalTo(-15);
            make.bottom.mas_equalTo(-4);
        }];
    }
    return self;
}

#pragma mark - getter and setter
- (UILabel *)title {
    if (!_title) {
        _title = [[UILabel alloc] init];
        _title.textColor = [UIColor colorWithHexString:@"#999999"];
        _title.font = [UIFont smallFont];
    }
    return _title;
}

@end

/*************************************** SelectTagsViewController *********************************************/


@interface SelectTagsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,SelectTagsCellFlowLayoutDelegate>

/**
 topHeaderView
 */
@property (nonatomic , strong) UIView *topHeaderView;
/**
 headerTitle
 */
@property (nonatomic , strong) UILabel *headerTitle;
/**
 headerDetail
 */
@property (nonatomic , strong) UILabel *headerDetail;
/**
 tagsCollectionView
 */
@property (nonatomic , strong) UICollectionView *tagsCollectionView;
/**
 footerView
 */
@property (nonatomic , strong) UIView * footerView;
/**
 bottomView
 */
@property (nonatomic , strong) UIView *bottomView;
/**
 bottomBtn
 */
@property (nonatomic , strong) UIButton *bottomBtn;
/**
 标签arr
 */
@property (nonatomic , strong) NSArray<UserTags *> *tagsData;

/**
 类型arr
 */
@property (nonatomic , strong) NSMutableDictionary<NSNumber *,NSString *> *selectedTagDic;

@end

@implementation SelectTagsViewController

#pragma mark - view life cycle
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setUpView];
}


#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}
- (void)initView {
    
    [self.view addSubview:self.tagsCollectionView];
    [self.tagsCollectionView addSubview:self.topHeaderView];
    [self.topHeaderView addSubview:self.headerTitle];
    [self.topHeaderView addSubview:self.headerDetail];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.bottomBtn];
}

- (void) initLayout {
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
    }];
    [self.bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(10);
        make.height.mas_equalTo(ScaleHeight(48));
        make.bottom.mas_equalTo(-IPHONEXBottomEdge);
    }];
    [self.tagsCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(self.baseNavView.bottom);
        make.bottom.mas_equalTo(self->_bottomView.mas_top);
    }];
    [self.topHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(-70);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 70));
    }];
    [self.headerTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(5);
    }];
    [self.headerDetail mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(self.headerTitle.mas_bottom).offset(6);
    }];
    
}

- (void) initAction {
    [self.bottomBtn addTarget:self action:@selector(confirmTapped) forControlEvents:UIControlEventTouchUpInside];
}

- (void)initData {
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] getUserTags] subscribeNext:^(UserTagsList * _Nullable tagsList) {
        @strongify(self);
        [self.aimsTags enumerateObjectsUsingBlock:^(id  _Nonnull tagIndex, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [tagsList.groupType enumerateObjectsUsingBlock:^(UserTags * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [obj.tagsList enumerateObjectsUsingBlock:^(UserTag * _Nonnull aimTagIndex, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if ([tagIndex integerValue] == [aimTagIndex.tagsId integerValue]){
                        
                        aimTagIndex.isSelect = @1;
                    }
                }];
            }];
        }];
        
        self.tagsData = tagsList.groupType;
        [self.tagsCollectionView reloadData];
        
    } error:^(NSError * _Nullable error) {
        
    }];
    
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.tagsData.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    UserTags *model = self.tagsData[section];
    return model.tagsList.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SelectTagsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SelectTagsCellID" forIndexPath:indexPath];
    UserTags *userTags = self.tagsData[indexPath.section];
    UserTag *userTag = userTags.tagsList[indexPath.row];
    cell.title.text = userTag.tagsName;
    if ([userTag.isSelect integerValue] == 1) {
        cell.title.textColor = [UIColor primaryColor];
        cell.layer.borderColor = [UIColor primaryColor].CGColor;
        [self.selectedTagDic setObject:userTag.tagsName forKey:userTag.tagsId];
    } else {
        cell.title.textColor = [UIColor colorWithHexString:@"#999999"];
        cell.layer.borderColor = [UIColor colorWithHexString:@"#cccccc"].CGColor;
    }
    if (indexPath.section == self.tagsData.count - 1 && indexPath.row == userTags.tagsList.count - 1) {
        NSString *title = [NSString stringWithFormat:@"确定(已选%lu个)",(unsigned long)self.selectedTagDic.allValues.count];
        [_bottomBtn setTitle:title forState:UIControlStateNormal];
    }
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SelectTagsCell *cell = (SelectTagsCell *)[collectionView cellForItemAtIndexPath:indexPath];
    UserTags *userTags = self.tagsData[indexPath.section];
    UserTag *userTag = userTags.tagsList[indexPath.row];
    if ([userTags.isSelect integerValue] == 1) { // 多选
        if ([self.selectedTagDic.allKeys containsObject:userTag.tagsId]) {
            [self.selectedTagDic removeObjectForKey:userTag.tagsId];
            cell.title.textColor = [UIColor colorWithHexString:@"#999999"];
            cell.layer.borderColor = [UIColor colorWithHexString:@"#cccccc"].CGColor;
        } else {
            [self.selectedTagDic setObject:userTag.tagsName forKey:userTag.tagsId];
            cell.title.textColor = [UIColor primaryColor];
            cell.layer.borderColor = [UIColor primaryColor].CGColor;
        }
    } else { // 单选
        for (int i = 0; i < userTags.tagsList.count; i++) {
            UserTag *item = userTags.tagsList[i];
            if ([item.tagsId isEqual:userTag.tagsId]) {
                if ([self.selectedTagDic.allKeys containsObject:item.tagsId]) {
                    [self.selectedTagDic removeObjectForKey:item.tagsId];
                    cell.title.textColor = [UIColor colorWithHexString:@"#999999"];
                    cell.layer.borderColor = [UIColor colorWithHexString:@"#cccccc"].CGColor;
                } else {
                    cell.title.textColor = [UIColor primaryColor];
                    cell.layer.borderColor = [UIColor primaryColor].CGColor;
                    [self.selectedTagDic setObject:userTag.tagsName forKey:userTag.tagsId];
                }
            } else {
                if ([self.selectedTagDic.allKeys containsObject:item.tagsId]) {
                    NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:i inSection:indexPath.section];
                    SelectTagsCell *tempCell = (SelectTagsCell *)[collectionView cellForItemAtIndexPath:tempIndexPath];
                    
                    [self.selectedTagDic removeObjectForKey:item.tagsId];
                    tempCell.title.textColor = [UIColor colorWithHexString:@"#999999"];
                    tempCell.layer.borderColor = [UIColor colorWithHexString:@"#cccccc"].CGColor;
                }
            }
        }
        
    }
    NSString *title = [NSString stringWithFormat:@"确定(已选%lu个)",(unsigned long)self.selectedTagDic.allValues.count];
    [self.bottomBtn setTitle:title forState:UIControlStateNormal];
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        TagsHeaderView *tagsHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SelectTagsHeaderID" forIndexPath:indexPath];
        UserTags *model = self.tagsData[indexPath.section];
        
        NSString *imageName = @"";
        NSString *titleName = model.tagsTypeName;
        
        switch (indexPath.section) {
            case 0: // 婚育
                imageName = @"tags_icon_yellow";
                //                titleName = @"婚育";
                break;
            case 1: // 年龄段
                imageName = @"tags_icon_deepgreen";
                //                titleName = @"年龄段";
                break;
            case 2: // 职业
                imageName = @"tags_icon_blue";
                //                titleName = @"职业";
                break;
            case 3: // 兴趣爱好
                imageName = @"tags_icon_littlegreen";
                //                titleName = @"兴趣爱好";
                break;
        }
        UIImageView *icon = [[UIImageView alloc] init];
        icon.image = [UIImage imageNamed:imageName];
        UILabel *title = [[UILabel alloc] init];
        title.textColor = [UIColor colorWithHexString:@"#262626"];
        title.font = [UIFont systemFontOfSize:17];
        title.text = titleName;
        HButtonView *buttonView = [[HButtonView alloc] initWithLeftIcon:icon title:title];
        tagsHeaderView.contentView = buttonView;
        return tagsHeaderView;
    } else {
        return nil;
    }
}


#pragma mark - SelectTagsCellFlowLayoutDelegate

- (NSString *)collectionViewItemSizeWithIndexPath:(NSIndexPath *)indexPath {
    UserTags *userTags = self.tagsData[indexPath.section];
    UserTag *userTag = userTags.tagsList[indexPath.row];
    return userTag.tagsName;
}


- (CGSize)collectionViewDynamicHeaderSizeWithIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(SCREEN_WIDTH, 50);
}



#pragma mark - target action

- (void)confirmTapped {
    if (self.selectedTagsBlock) {
        self.selectedTagsBlock(self.selectedTagDic);
    }
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - getter methods

- (UICollectionView *)tagsCollectionView {
    if (!_tagsCollectionView) {
        SelectTagsCellFlowLayout *flowLayout = [[SelectTagsCellFlowLayout alloc] init];
        flowLayout.itemInset = UIEdgeInsetsMake(0, 20, 0, 20);
        flowLayout.interitemSpacing = 10;
        flowLayout.lineSpacing = 10;
        flowLayout.delegate = self;
        
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _tagsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        [_tagsCollectionView registerClass:[SelectTagsCell class] forCellWithReuseIdentifier:@"SelectTagsCellID"];
        [_tagsCollectionView registerClass:[TagsHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SelectTagsHeaderID"];
        _tagsCollectionView.delegate = self;
        _tagsCollectionView.dataSource = self;
        _tagsCollectionView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
        _tagsCollectionView.contentInset = UIEdgeInsetsMake(70, 0, 0, 0);
    }
    return _tagsCollectionView;
}


- (UIView *)topHeaderView {
    if (!_topHeaderView) {
        _topHeaderView = [[UIView alloc] init];
    }
    return _topHeaderView;
}


- (NSArray<UserTags *> *)tagsData {
    if (!_tagsData) {
        _tagsData = [NSArray array];
    }
    return _tagsData;
}


- (NSMutableDictionary<NSNumber *,NSString *> *)selectedTagDic {
    if (!_selectedTagDic) {
        _selectedTagDic = [NSMutableDictionary dictionary];
    }
    return _selectedTagDic;
}


- (UILabel *)headerTitle {
    if (!_headerTitle) {
        _headerTitle = [[UILabel alloc] init];
        _headerTitle.textColor = [UIColor colorWithHexString:@"#262626"];
        _headerTitle.font = [UIFont xxLargerFont];
        _headerTitle.text = @"选择你的标签";
    }
    return _headerTitle;
}


- (UILabel *)headerDetail {
    if (!_headerDetail) {
        _headerDetail = [[UILabel alloc] init];
        _headerDetail.textColor = [UIColor colorWithHexString:@"#808080"];
        _headerDetail.font = [UIFont systemFontOfSize:15];
        _headerDetail.text = @"你可以选择适合你的标签，方便豚友更了解你";
    }
    return _headerDetail;
}


- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
    }
    return _bottomView;
}

- (UIButton *)bottomBtn {
    if (!_bottomBtn) {
        _bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _bottomBtn.backgroundColor = [UIColor primaryColor];
        [_bottomBtn setBackgroundImage:[UIImage imageNamed:@"login_loginbtn_default"] forState:UIControlStateNormal];
        [_bottomBtn setBackgroundImage:[UIImage imageNamed:@"login_loginbtn_input"] forState:UIControlStateSelected];
        NSString *title = [NSString stringWithFormat:@"确定(已选%lu个)",(unsigned long)self.selectedTagDic.count];
        [_bottomBtn setTitle:title forState:UIControlStateNormal];
        _bottomBtn.layer.cornerRadius = 4;
        _bottomBtn.layer.masksToBounds = YES;
    }
    return _bottomBtn;
}

@end

